package terminal;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

import common.TVConsts;

public class Terminal {
	static final int CH1 = 0, CH2 = 1, CH3 = 2;

	byte[] data = null;

	SocketThread thread = new SocketThread();
	MulticastSocket mcsock = null;
	static InetAddress groups[] = new InetAddress[3];
	InetAddress oldGroup = null;

	public Terminal() {
		try {
			groups[0] = InetAddress.getByName(TVConsts.MC_CH1_ADDRESS);
			groups[1] = InetAddress.getByName(TVConsts.MC_CH2_ADDRESS);
			groups[2] = InetAddress.getByName(TVConsts.MC_CH3_ADDRESS);

			oldGroup = groups[1]; // default channel
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	public boolean start() {
		try {
			mcsock = new MulticastSocket(TVConsts.MC_PORT);
			mcsock.joinGroup(oldGroup);

			thread.start(); // 开启线程接收
			return true;
		} catch (IOException e) {
//			e.printStackTrace();
			System.out.println(e);
			return false;
		}
	}

	public void stop() {
		try {
			mcsock.leaveGroup(oldGroup);
			thread.stop(); // 结束线程
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			mcsock.close();
		}
	}

	public byte[] getData() {
		return data;
	}

	public void setChannel(int channel) {
		try {
			InetAddress newGroup = null;
			switch (channel) {
			case CH1:
				newGroup = groups[0];
				break;
			case CH2:
				newGroup = groups[1];
				break;
			case CH3:
				newGroup = groups[2];
				break;
			}
			if (oldGroup != newGroup) {
				mcsock.leaveGroup(oldGroup);
				mcsock.joinGroup(newGroup);
				oldGroup = newGroup;
			}
		} catch (Exception e) {
			System.out.println(e);
		}

	}

	private class SocketThread extends Thread {
		public void run() {
			try {
				while (true) {
					byte[] buf = new byte[65507];
					DatagramPacket pkt = new DatagramPacket(buf, buf.length);

					mcsock.receive(pkt);
					ByteBuffer buffer = ByteBuffer.allocate(pkt.getLength());
					buffer.put(pkt.getData(), 0, pkt.getLength());
					data = buffer.array();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
